﻿using System;
using System.IO;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace NaturalKeySpike {
    public interface INhibernateSessionFactoryHelper {
        ISession OpenSession();
    }

    public class NhibernateSessionFactoryHelper : INhibernateSessionFactoryHelper {
        private static readonly Lazy<ISessionFactory> _sessionFactory = new Lazy<ISessionFactory>(CreateSessionFactory);

        public ISession OpenSession() {
            return _sessionFactory.Value.OpenSession();
        }

        private static ISessionFactory CreateSessionFactory() {
            try {
                return Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2008.ConnectionString(b => b.FromConnectionStringWithKey("db")))
                    .Mappings(map => {
                        map.FluentMappings.AddFromAssembly(typeof(NhibernateSessionFactoryHelper).Assembly);
                        ExportMappings(map);
                    })
                    .BuildSessionFactory();
            }
            catch (Exception ex) {
                Console.WriteLine(ex);
                throw;
            }
        }

        private static void ExportMappings(MappingConfiguration map) {
            var path = @"..\..\..\mappings";

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            map.FluentMappings.ExportTo(path);
            map.AutoMappings.ExportTo(path);
        }
    }
}
